package com.noassertions.web;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.noassertions.data.DAOInterface;
import com.noassertions.domain.Fit;
import com.noassertions.domain.User;

@Controller
public class FitManager {

	protected final Log log = LogFactory.getLog(getClass());
	private DAOInterface dao;

    @Autowired
    public FitManager(DAOInterface dao) {
        this.dao = dao;
    }  
  
    /**
     * If no fit id is specified, return all fits owned by user
     * 
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/fit/manage", method = RequestMethod.GET)
    public String getFits(Model model)
    {
    	// TODO: factor this business out. should be handled somewhere above us
    	UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	User user = dao.getUserByemailAddress(principal.getUsername());
    	model.addAttribute("emailAddress", user.getEmailaddress());

    	ArrayList fits = dao.getFitsByUserId(user.getUserid());
    	log.debug("Found " + fits.size() + " fits for " + user.getEmailaddress());
    	model.addAttribute("fits", fits);
    	return "fitmanage";
    }
   
    /**
     * If we get a request for a specific fit id, just return that one
     */
	@RequestMapping(value = "/fit/managr/{fitid}", method = RequestMethod.GET)
	public String getFit(@PathVariable Integer fitid, Model model)
	{
		Fit fit = dao.getFitByFitId(fitid);
		model.addAttribute("fit", fit);
		return "fiteditor";
	}
}